package com.example.administrator.dc.Activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.dc.Bean.Usermessage;
import com.example.administrator.dc.Class.BlueFilter;
import com.example.administrator.dc.Class.GrayFilter;
import com.example.administrator.dc.Class.GreenFilter;
import com.example.administrator.dc.Class.Polaroid;
import com.example.administrator.dc.Class.RedFilter;
import com.example.administrator.dc.Class.order_time;
import com.example.administrator.dc.Class.typecolor;
import com.example.administrator.dc.R;
import com.example.administrator.dc.Service.UserService;
import com.example.administrator.dc.dialog.UpdateDialog;
import com.example.administrator.dc.helper.RoundImageView;
import com.example.administrator.dc.model.Contants;
import com.example.administrator.dc.util.SexListener;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import static com.example.administrator.dc.Activity.UploadActivity.getRealPathFromUri;

public class PersonCenterActivity extends BaseActivity {
              private RoundImageView userphoto;
    private TextView username;
    private TextView usergender;
    private TextView usercity;
    private static final int REQUEST_CODE_CAPTURE_CAMEIA = 1;
    private static final int REQUEST_CODE_PICK_IMAGE = 1;
    private TextView userProvince;
    private  TextView userschool;
    private LinearLayout gender;
    private LinearLayout name;
    private LinearLayout school;
    private  String fileName;
    String userid;
    int sexId;
    private SexListener listener=new SexListener() {
        @Override
        public void onSuccess(String sex,int gender) {
            usergender.setText(sex);
            sexId =gender;
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_person_center);
         initViews();
         getDatas();
        getUser();
        initEvets();


        //这句就是添加我们自定义的分隔线
//addItemDecoration(new MyDecoration(MyFollowActivity.this, MyDecoration.VERTICAL_LIST));
    }
    private void initViews()
    {
        userphoto=(RoundImageView)findViewById(R.id.person_userphoto_img);
        username=(TextView)findViewById(R.id.person_username_content);
        usergender=(TextView)findViewById(R.id.person_gender_content);
        usercity=(TextView)findViewById(R.id.person_city_content);
        userProvince=(TextView)findViewById(R.id.person_province_content);
        userschool=(TextView)findViewById(R.id.person_school_contnet);
        gender=(LinearLayout)findViewById(R.id.person_linear_gender);
        name=(LinearLayout)findViewById(R.id.person_linear_name);
        school=(LinearLayout)findViewById(R.id.person_linear_school);

    }
    private void  getDatas()
    {
        SharedPreferences sp = getApplication().getSharedPreferences("UserInfo", getApplication().MODE_PRIVATE);
         userid =sp.getString("user_id", null);
       // userphoto= (RoundImageView) findViewById(R.id.touxiang);
        Retrofit retrofit=new Retrofit.Builder().baseUrl(Contants.BASE_URL1).
                addConverterFactory(GsonConverterFactory.create()).build();
        UserService service=retrofit.create(UserService.class);
        Call<Usermessage> call= service.usermessage(userid);
        call.enqueue(new Callback<Usermessage>() {
            @Override
            public void onResponse(Call<Usermessage> call, Response<Usermessage> response) {

                  Usermessage res=response.body();

                sexId =res.getGender();
                if (!"".equals(response.body().getPic()))
                    Picasso.with(PersonCenterActivity.this).load(response.body().getPic()).into(userphoto);
                    username.setText(res.getAliasname());
                if (1==res.getGender())
                {
                    usergender.setText("女");
                }
                else
                {
                    usergender.setText("男");
                }
                userProvince.setText(res.getProvince());
                usercity.setText(res.getCity());
                userschool.setText(res.getSchool());




            }

            @Override
            public void onFailure(Call<Usermessage> call, Throwable t) {

            }
        });

            }

    private void getUser(){
        SharedPreferences sp = getSharedPreferences("UserInfo", MODE_PRIVATE);
        userid = sp.getString("user_id", null);


    }
    public  void initEvets()
    {
        final UpdateDialog dialog=new UpdateDialog();
         gender.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                dialog.select(PersonCenterActivity.this,sexId,listener,userid);
                // select();
             }
         });
        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent(PersonCenterActivity.this,EditnameActivity.class);
                intent.putExtra("user_name",username.getText().toString());
                startActivity(intent);
            }
        });
        school.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent =new Intent(PersonCenterActivity.this,EditSchoolActivity.class);
                intent.putExtra("school",userschool.getText().toString());
                startActivity(intent);
            }
        });

        userphoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                select();
            }
        });


        
    }
    private void select() {
        final int[] yourChoice = new int[1];

        final String[] items = {"拍照", "本地图片"};
        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(PersonCenterActivity.this);
        singleChoiceDialog.setTitle("选取照片方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice[0] = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice[0] != -1) {
                            if (items[yourChoice[0]].equals("拍照")) {
                                getImageFromCamera();


                            }
                            if (items[yourChoice[0]].equals("本地图片")) {

                                Intent intent = new Intent(Intent.ACTION_PICK);
                                intent.setType("image/*");//相片类型
                                startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
                                Toast.makeText(PersonCenterActivity.this,
                                        "你选择了" + items[yourChoice[0]],
                                        Toast.LENGTH_SHORT).show();

                            }

                        }
                    }
                });
        singleChoiceDialog.show();
    }
    protected void getImageFromCamera() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
            startActivityForResult(getImageByCamera, REQUEST_CODE_CAPTURE_CAMEIA);
        } else {
            Toast.makeText(getApplicationContext(), "请确认已经插入SD卡", Toast.LENGTH_LONG).show();
        }
    }
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE) {
            Uri uri = data.getData();
            if (uri == null) {
                //use bundle to get data
                Bundle bundle = data.getExtras();
                if (bundle != null) {
                    SharedPreferences sp = getApplication().getSharedPreferences("UserInfo", getApplication().MODE_PRIVATE);
                    String userid = sp.getString("user_id", null);
                    final Bitmap photo = (Bitmap) bundle.get("data");
                    final Bitmap[] image = new Bitmap[1];

                 /*   GrayFilter grayFilter=new GrayFilter();
                    grayFilter.changeToGray(photo);*/
                    // Send.setImageBitmap( grayFilter.changeToGray(photo));
                }
            }
            else {
                uri = data.getData();
                if (uri != null) {
                    //use bundle to get data
                    SharedPreferences sp = getApplication().getSharedPreferences("UserInfo", getApplication().MODE_PRIVATE);
                    String userid = sp.getString("user_id", null);
                    String mingzi=  getRealPathFromUri(this,uri);
                    int y= mingzi.lastIndexOf("/");
                    fileName=mingzi.substring(y+1);
                    final Bitmap photo = getDiskBitmap(getRealPathFromUri(this,uri));
                    saveImage(photo, "111");
                    //      Send.setImageDrawable(this.getDrawable(R.drawable.camera));
                  /*  UploadUtil u=new UploadUtil();
                    u.Upload(photo,"111",userid);*/
                    //  saveImage(photo, "123431");

                } else {
                    Toast.makeText(getApplicationContext(), "err****", Toast.LENGTH_LONG).show();
                    return;
                }
            }
        }
        //to do find the path of pic by uri

    }
    public void saveImage(Bitmap photo, String spath) {
        File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            Bitmap endBit = Bitmap.createScaledBitmap(photo, 400, 400, true); //创建新的图像大小
            endBit.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    private Bitmap getDiskBitmap(String url)
    {
        Bitmap bitmap = null;
        try
        {
            File file = new File(String.valueOf(url));
            if(file.exists())
            {
                bitmap = BitmapFactory.decodeFile(String.valueOf(url));
            }
        } catch (Exception e)
        {
            // TODO: handle exception
        }

        return bitmap;
    }
   // int yourChoice ;
   /* public void select() {

        final String[] items = {"男", "女"};
        yourChoice = -1;
        final AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(PersonCenterActivity.this);
        //singleChoiceDialog.setTitle("选取照片方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, sexId,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, int which) {
                        yourChoice=which;
                        String s = String.valueOf(yourChoice);
                        if (yourChoice!=-1)
                        {
                            UsersModel usersModel =new UsersModel();
                            Call <EditGender> call= usersModel.editgender(userid, s);
                            call.enqueue(new Callback<EditGender>() {
                                @Override
                                public void onResponse(Call<EditGender> call, Response<EditGender> response) {
                                    if (1==response.body().getStatus())
                                    {
                                        Toast.makeText(PersonCenterActivity.this,"修改成功！",Toast.LENGTH_SHORT).show();
                                    }
                                    dialog.dismiss();
                                }
                                @Override
                                public void onFailure(Call<EditGender> call, Throwable t) {

                                }
                            });
                        }

                    }
                });
        singleChoiceDialog.show();

    }*/


    @Override
    protected void onResume() {
        super.onResume();
        getDatas();
    }
}



